﻿using System;
using BlazorDownloadFile;
using BootstrapBlazor.Components;
using iTeamyou.LTS.Core.Models;
using iTeamyou.LTS.Core.Services;
using Microsoft.AspNetCore.Components;
using System.Diagnostics.CodeAnalysis;
using iTeamyou.LTS.UI.Utils;
using Microsoft.AspNetCore.Components.Forms;
using System.ComponentModel;
using iTeamyou.LTS.UI.Models;
using iTeamyou.LTS.UI.Shared.Components;
using Microsoft.AspNetCore.Components.Web;

namespace iTeamyou.LTS.UI.Pages.Archive.Supplier
{
	public partial class SupplierComponent
	{
        [Inject]
        [NotNull]
        private MessageService? MessageService { get; set; }

        [Inject] ToastService Toast { get; set; }
      
        [Inject] SupplierService? SupplierService { get; set; }
        [Inject] SharedService? SharedService { get; set; }

        [Inject]
        [NotNull]
        private DialogService? DialogService { get; set; }

        [Parameter]
        public Action? OnClose { get; set; }

        [Parameter]
        public string SupplierId { get; set; }

        [Parameter]
        public string UserId { get; set; }

        //新建或编辑
        [Parameter]
        public DocStatus DocStatus { get; set; }
        public bool IsButtonDisabled { get; set; }
        public bool IsDeleteDisabled { get; set; }
        public bool IsFieldReadOnly { get; set; }
        public bool IsSaveDisabled { get; set; }

        public string deleteMessage { get; set; }

        [Parameter]
        public Core.Models.Supplier? SupplierModel { get; set; }

        public List<SupplierLicense>? SelectedLicense { get; set; } = new();

        protected override async void OnInitialized()
        {
            PageOpInit();

            if (SupplierModel == null)
                SupplierModel = new Core.Models.Supplier();
            else
            {
                var licenses = SupplierModel.SupplierLicenses;
                SupplierModel = SupplierService.Get(SupplierModel.Id);
                SupplierModel.SupplierLicenses = licenses;
            }
            
            deleteMessage = GetDeleteMessage();

            base.OnInitialized();
        }

        protected override void OnParametersSet()
        {
            base.OnParametersSet();
        }

        private void PageOpInit()
        {
            switch (DocStatus)
            {
                case DocStatus.New:
                    IsButtonDisabled = true;
                    IsFieldReadOnly = false;
                    IsDeleteDisabled = true;
                    IsSaveDisabled = false;
                    break;
                case DocStatus.Edit:
                    IsButtonDisabled = false;
                    IsFieldReadOnly = true;
                    IsDeleteDisabled = false;
                    IsSaveDisabled = false;
                    break;
                case DocStatus.Archive:
                    IsButtonDisabled = true;
                    IsFieldReadOnly = true;
                    IsDeleteDisabled = true;
                    IsSaveDisabled = true;
                    break;
                case DocStatus.View:
                    IsButtonDisabled = true;
                    IsFieldReadOnly = true;
                    IsDeleteDisabled = true;
                    IsSaveDisabled = true;
                    break;
                default:
                    break;
            }
        }

        private Task<QueryData<SupplierLicense>> OnLicenseQueryAsync(QueryPageOptions options)
        {
            StateHasChanged();
            //IEnumerable<SupplierLicense> supplierLicenses = SupplierService.GetLicenses(SupplierModel.Id);
            //var supplierLicenses = (IEnumerable<SupplierLicense>)SupplierModel.SupplierLicenses;
            var licenses = (IEnumerable<SupplierLicense>)SupplierModel.SupplierLicenses;
            var total = 0;
            if (licenses != null)
            {
                // 排序
                var isSorted = false;
                if (!string.IsNullOrEmpty(options.SortName))
                {
                    if (options.SortOrder == SortOrder.Asc)
                        licenses = licenses.OrderBy(g => SharedService.GetPropertyValue(g, options.SortName));
                    else if (options.SortOrder == SortOrder.Desc)
                        licenses = licenses.OrderByDescending(g => SharedService.GetPropertyValue(g, options.SortName));
                    else
                        licenses = licenses.OrderByDescending(g => g.LastModifiedOn);
                    isSorted = true;
                }
                else
                {
                    licenses = licenses.OrderByDescending(g => g.LastModifiedOn);
                }

                // 设置记录总数
                total = licenses.Count();
            }

            return Task.FromResult(new QueryData<SupplierLicense>()
            {
                Items = licenses,
                TotalCount = total
            });
        }

        private async Task OnValidSubmit(EditContext model)
        {
            var supplierCheck = SupplierService.Get(SupplierModel.Id);
            if (supplierCheck != null && DocStatus == DocStatus.New)
            {
                await MessageService.Show(new MessageOption()
                {
                    Content = $"供应商信息保存失败，原因：相同的供应商编号已存在",
                    Icon = "fa-solid fa-circle-error",
                    Color = Color.Danger,
                    ShowDismiss = true
                });
                return;
            }

            SupplierModel.LastModifiedBy = UserId;
            SupplierModel.LastModifiedOn = DateTime.Now;

            if (DocStatus == DocStatus.New)
            {
                SupplierModel.Id = Guid.NewGuid().ToString("N");
                SupplierModel.CreatedBy = UserId;
                SupplierModel.CreatedOn = DateTime.Now;
            }

            SupplierService.Save(SupplierModel);
            StateHasChanged();

            SharedService.CallRequestRefresh();
            await Task.CompletedTask;
            OnClose?.Invoke();
            await MessageService.Show(new MessageOption()
            {
                Content = "保存数据成功",
                Icon = "fa-solid fa-circle-info",
                Color = Color.Success,
                ShowDismiss = true
            });
        }

        private async Task OnInvalidSubmit(EditContext context)
        {
            await MessageService.Show(new MessageOption()
            {
                Content = $"保存失败，字段验证未通过",
                Icon = "fa-solid fa-circle-error",
                Color = Color.Danger,
                ShowDismiss = true
            });
            return;
        }

        private async Task DeleteSupplier(Core.Models.Supplier supplier)
        {
            var suppliers = new List<Core.Models.Supplier>
            {
                supplier
            };
            SupplierService.Delete(suppliers);
            StateHasChanged();
            SharedService.CallRequestRefresh();
            await Task.CompletedTask;
            OnClose?.Invoke();
            await MessageService.Show(new MessageOption()
            {
                Content = "删除供应商成功",
                Icon = "fa-solid fa-circle-info",
                Color = Color.Success,
                ShowDismiss = true
            });
        }

        private async Task View(SupplierLicense supplierLicense)
        {
            var op = new DialogOption()
            {
                Title = "查看证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(LicenseComponent.DocStatus)] = DocStatus.View,
                [nameof(LicenseComponent.UserId)] = UserId,
                [nameof(LicenseComponent.Supplier)] = SupplierModel,
                [nameof(LicenseComponent.LicenseModel)] = supplierLicense,
                [nameof(LicenseComponent.OnLicenseSaved)] = EventCallback.Factory.Create<Core.Models.Supplier>(this, OnLicenseSavedHandler)
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task AddLicense()
        {
            var op = new DialogOption()
            {
                Title = "添加证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(LicenseComponent.DocStatus)] = DocStatus.New,
                [nameof(LicenseComponent.UserId)] = UserId,
                [nameof(LicenseComponent.Supplier)] = SupplierModel,
                [nameof(LicenseComponent.OnLicenseSaved)] = EventCallback.Factory.Create<Core.Models.Supplier>(this, OnLicenseSavedHandler)
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task EditLicense(SupplierLicense supplierLicense)
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(LicenseComponent.DocStatus)] = DocStatus,
                [nameof(LicenseComponent.UserId)] = UserId,
                [nameof(LicenseComponent.Supplier)] = SupplierModel,
                [nameof(LicenseComponent.LicenseModel)] = supplierLicense,
                [nameof(LicenseComponent.OnLicenseSaved)] = EventCallback.Factory.Create<Core.Models.Supplier>(this, OnLicenseSavedHandler)
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task EditLicenseBtn()
        {
            var op = new DialogOption()
            {
                Title = "编辑证照",
                ShowFooter = false
            };
            op.BodyTemplate = BootstrapDynamicComponent.CreateComponent<LicenseComponent>(new Dictionary<string, object?>
            {
                [nameof(LicenseComponent.OnClose)] = new Action(async () => await op.CloseDialogAsync()),
                [nameof(LicenseComponent.DocStatus)] = DocStatus,
                [nameof(LicenseComponent.UserId)] = UserId,
                [nameof(LicenseComponent.Supplier)] = SupplierModel,
                [nameof(LicenseComponent.LicenseModel)] = SelectedLicense.FirstOrDefault(),
                [nameof(LicenseComponent.OnLicenseSaved)] = EventCallback.Factory.Create<Core.Models.Supplier>(this, OnLicenseSavedHandler)
            }).Render();
            op.IsScrolling = true;
            await DialogService.Show(op);
        }

        private async Task DeleteLicenses(List<SupplierLicense> licenses)
        {
            foreach (var license in licenses)
            {
                var opTarget = SupplierModel.SupplierLicenses.Where(l => l.Id == license.Id).FirstOrDefault();
                if (opTarget.OperationType == 0)
                  SupplierModel.SupplierLicenses.Remove(license);
                else
                    opTarget.OperationType = LicenseOp.Delete;
            }    

            //SupplierService.Save(SupplierModel);
            StateHasChanged();
            SharedService.CallRequestRefresh();
            await Task.CompletedTask;
            await MessageService.Show(new MessageOption()
            {
                Content = $"删除了{licenses.Count}个证照",
                Icon = "fa-solid fa-circle-info",
                Color = Color.Success,
                ShowDismiss = true
            });
        }

        private Task SelectChanged(List<SupplierLicense> licenses)
        {
            SelectedLicense= licenses;
            StateHasChanged();
            return Task.CompletedTask;
        }

        private string GetDeleteMessage()
        {
            return $"你确认要供应商记录吗";
        }

        private string GetLicenseTypeName(string id)
        {
            var licenseTypes = SupplierService.GetLicenseType("supplier");
            if (licenseTypes != null && licenseTypes.Any())
                return licenseTypes.FirstOrDefault(l => l.TypeId == id).TypeName;
            return string.Empty;
        }

        public Task OnLicenseSavedHandler(Core.Models.Supplier supplier)
        {
            SupplierModel = supplier;
            StateHasChanged();
            return Task.CompletedTask;
        }
    }
}

